#!/usr/bin/python
#-*- coding: utf-8 -*-

import os
import sys
import readline
import MySQLdb
import re
import json
import random
import logging
import urllib
import urllib2



username = raw_input('请输入登录名： ')
passwd = raw_input('请输入密码： ')
name_file = file('username_list.txt','rb')
username_list = []
passwd_list = []
name_passwd_list = []
lock_name_file = file('lock_name_file.txt','rb')
lock_name_list = []
i = 0

class User:
    """docstring for User"""

    def __init__(self):
        pass





    # 注册类方法
    # 1 用户名或密码是否合法
    def user_pass_illegal(self, username, passwd):
        isMatch = bool(re.match(r"^[a-zA-Z](([a-zA-Z0-9]*\.[a-zA-Z0-9]*)|[a-zA-Z0-9]*)[a-zA-Z]@([a-z0-9A-Z]+\.)+[a-zA-Z]{2,}$",input(username),re.VERBOSE))
        if isMatch:
            print ("用户注册成功")
        else:
            print ("用户注册失败")

        return isMatch

        isMatch = bool(re.match(r"[a-zA-Z0-9]{8}",input(passwd),flags=0))

        if isMatch:
            type = [False,False,False]

            for i in range(0,8):
                temp = input(passwd)[i]
                if ord(temp) >= ord('0') and ord(temp) <= ord('9'):
                    type[0] = True
                elif ord(temp) >= ord('a') and ord(temp) <= ord('z'):
                    type[1] = True
                elif ord(temp) >= ord('A') and ord(temp) <= ord('Z'):
                    type[2] = True

            for i in type:
                if i is False:
                    isMatch = False
                    break


        if isMatch:
            for i in range(0,7):
                temp = input(passwd)[i]
                for j in range(i + 1,8):
                    if input(passwd)[j] == temp:
                        isMatch = False
                        break




        if isMatch:
            print ("密码注册成功")
        else:
            print ("密码注册失败")
        return isMatch





    # 2 用户是否存在
    def user_esxits(self, phone):
        try:
            conn = MySQLdb.connect(host = "211.166.22.190", user = "zwhset", passwd ="jfpython",db = "python3",port = 3306)
            cur = conn.cursor()
            cur.execute('SELECT phone FROM user WHERE phone="phone"')
            result = cur.fetchall()
            cur.close()
            conn.close()

        except MySQLdb.Error,e:
            print "MySQLdb error %s :%s" %(e.args[0],e.args[1])

        data = []
        #print result

        for i in range(0,len(result)):
            data.append(result[i][0])
        #print data

        for line in open('name_file'):
            if line.strip() in data:
                print line,1
            else:
                print line,0







    # 3 确认密码是否相同
    def check_pass(self, passwd, en_passwd):
        try:
            conn = MySQLdb.connect(host="211.166.22.190", user="zwhset", passwd="jfpython", db="python3", port=3306)
            cur = conn.cursor()
            cur.execute('SELECT passwd FROM user WHERE passwd="passwd"')
            result = cur.fetchall()
            cur.close()
            conn.close()

        except MySQLdb.Error, e:
            print "MySQLdb error %s :%s" % (e.args[0], e.args[1])

        data = []
        # print result

        for i in range(0, len(result)):
            data.append(result[i][0])
        # print data

        for line in open('name_file'):
            if line.strip() in data:
                print line, 1
            else:
                print line, 0
        pass



    # 4 注册提醒功能
    def register_notiy(self):
       pass

    # 5 记录日志
    def register_log(self):
        self.logger = logging.getLogger('register_log')
        self.logger.setLevel(logging.DEBUG)

        fh = logging.FileHandler('register_log.log')
        fh.setLevel(logging.DEBUG)

        ch = logging.StreamHandler()
        ch.setLevel(logging.DEBUG)

        # 定义handler的输出格式
        # formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')

        formatter = format_dict[int(loglevel)]
        fh.setFormatter(formatter)
        ch.setFormatter(formatter)

        self.logger.addHandler(fh)
        self.logger.addHandler(ch)


        return self.logger





    # 6 会话保持
    # 登陆类方法
    # 1 验证用户名是否存在 调用注册的方法
    # 2 是否被激活 验证用户名和密码是否正确
    def user_isalive(self,username):
        pass


    def check_user_pass(self, username, passwd):
        if self.user_isalive:
            if passwd == en_passwd:
                return True




    # 3 异地登陆提醒
    def diff_ip(self):
        if online_user:
            another = SendToClientPackage('anotherlogin')
            another.status = 1
            online_user.connection.send_message(json.dumps( another , cls= ComplexEncoder ))
        pass


    def login_log(self):
        self.logger = logging.getLogger('login_log')
        self.logger.setLevel(logging.DEBUG)

        fh = logging.FileHandler('login_log.log')
        fh.setLevel(logging.DEBUG)

        ch = logging.StreamHandler()
        ch.setLevel(logging.DEBUG)

        # 定义handler的输出格式
        # formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')

        formatter = format_dict[int(loglevel)]
        fh.setFormatter(formatter)
        ch.setFormatter(formatter)

        self.logger.addHandler(fh)
        self.logger.addHandler(ch)

        return self.logger
        pass



    # 5 密码错误过多锁定
    def user_lock(self, username):
        flag = True
        counter = 0
        ##三次失败后，flag = Flase
        while flag:
            if counter > 2:
                passwd = raw_input('请输入用户%s的密码：' %username)
                counter = counter + 1
                if passwd == passwd_list[username_index]:
                    print "恭喜，登陆成功！"
                else:
                    print '对不起，密码错误，请查正后在登陆！'
                break;

            ##用户名和密码的比较




    # 其它方法
    # 1 验证验证码
    def chech_code(self, code,len=6):
        ''' 随机生成6位的验证码 '''
        code_list = []
        for i in  range(10):
            code_list.append(str(i))

        for i in range(65,91):
            code_list.append(chr(i))

        for i in  range(97,23):
            code_list.append(chr(i))

        myslice = random.sample(code_list,len)

        chech_code = ''.join(myslice)
        return  chech_code

    # 2 发送信息检测帐号
    def send_user_notiy(self, username):
        send_user_notiy = "http://www.810086.com.cn/jk.aspx"
        params = {"zh":"china", "mm":"china@10086",  "hm":phoneID,"nr":msg,"sms_type":88}
        postData = urllib.urlencode(params)
        req = urllib2.Request(send_user_notiy,postData)
        req.add_header('Content-Type',"application/x-www-form-urlencoded")
        respone = urllib2.urlopen(req)
        res = respone.read()
        return res






    def change_passwd(self, username):
        passwd = input('Password:')
        passwd_correct = passwd == passwd_list[-1]
        passwd_reset = passwd == passwd_list[0]
        if passwd_correct:
            print ('Login success!')
        elif passwd_reset:
            new_passwd = input('Enter a new password:')
            passwd_list.append(new_passwd)
            print ('Your password has changed successfully!')
            change_passwd()

        else:
            print ('Wrong password or invalid input!')
            change_passwd()

    change_passwd()




    def foget_passwd(self, username):
        if self.send_user_notiy(username):
            if self.change_passwd(username):
                return True

    # 注册入口
    def register(self, username, passwd, en_passwd):
        if not self.user_pass_illegal(username, passwd):
            return False
        if not self.user_esxits(username):
            return False
        if not self.check_pass(passwd, en_passwd):
            return False
        try: #不管有没有执行成功，我们的用户注册功能正常
            if not self.register_notiy(username):
                return False
            if not self.register_log(register_log_content):
                return False
        except Exception, e:
            raise e
        finally:
            return True

    # 登陆入口
    def login(self, username, passwd):
        if not self.user_esxits(username):
            return False
        if not self.user_isalive(username):
            return False
        if not check_user_pass(username, passwd):
            return False
        if not self.user_lock(username):
            return False
        try:
            if self.diff_ip(username, ip):
                pass
        except Exception, e:
            raise e
        finally:
            pass